package com.jz.digital.xiaoshou_chuku

import com.jz.digital.base.BasePresenter
import com.jz.digital.bean.BaseEntity
import com.jz.digital.bean.ServerBean
import com.jz.digital.listener.ApiCallback
import com.jz.digital.net.DataApi
import com.jz.digital.utils.AccountManagerHelper
import com.jz.digital.utils.ErrorCode
import com.jz.digital.utils.GreenDaoUtils
import com.jz.digital.utils.GsonUtil
import com.jz.digital.utils.LogUtils

/**
 * 销售出库
 */
class XiaoShouChuKuPresenter : BasePresenter<IXiaoShouChuKuView>() {
    private val tag = "XiaoShouChuKuPresenter"
    val mChePaiList = mutableListOf<ServerBean.GXInfo>()
    val mDataList = mutableListOf<ServerBean.MailChuKuResponseItem>()
    var mScanResponse: MutableList<ServerBean.MailChuKuResponseItem>? = null
    private var wkId = ""
    private var wkName = ""

    init {
        val userInfo = GreenDaoUtils.getUserInfo(AccountManagerHelper.getInstance().userId)
        wkId = userInfo.userId
        wkName = userInfo.userName
    }

    fun initData() {
        getChePaiList()
        queryTemp()
    }

    fun getChePaiList() {
        LogUtils.d(tag, "开始从服务器获取车牌列表")
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 5, type = "CP"))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>?>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(
                        tag,
                        "从服务器获取车牌列表成功 response=${GsonUtil.toJson(response)}"
                    )
                    if (response != null && !response.data.isNullOrEmpty()) {
                        for (itemBean in response.data!!) {
                            if (itemBean.basId.isNullOrEmpty()) continue
                            val tempName = itemBean.basId
                            itemBean.basId = itemBean.basName
                            itemBean.basName = tempName
                            mChePaiList.add(itemBean)
                        }
                    }
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(tag, "从服务器获取车牌列表失败 code=$code,message=$message")
                }

            })
    }

    /**
     * 获取临时表
     */
    private fun queryTemp(){
        view?.showLoading()
        DataApi.api.queryDeTmp(ServerBean.TempBean(wkId)).enqueue(object :ApiCallback<BaseEntity<MutableList<ServerBean.MailChuKuResponseItem>?>>() {
            override fun onSuccess(response: BaseEntity<MutableList<ServerBean.MailChuKuResponseItem>?>?) {
                LogUtils.d(tag, "销售出库获取临时表成功 response=${GsonUtil.toJson(response)}")
                if (response != null && response.data != null){
                    mScanResponse = response.data
                    mDataList.clear()
                    if (!response.data.isNullOrEmpty()) {
                        for (itemData in response.data!!) {
                            mDataList.add(
                                ServerBean.MailChuKuResponseItem(
                                    id = itemData.id,
                                    userId = itemData.userId, prodNo = itemData.prodNo,
                                    qty = itemData.qty, preQty = itemData.preQty,
                                    custId = itemData.custId, custName = itemData.custName,
                                    custPo = itemData.custPo, itemNo = itemData.itemNo,
                                    itemDesc = itemData.itemDesc, specs = itemData.specs, stkQty = itemData.stkQty
                                )
                            )
                        }
                    }
                    view?.notifyAdapter()
                }

                view?.dismissLoading()
            }

            override fun onError(t: Throwable?, code: Int, message: String?) {
                view?.dismissLoading()
            }

        })
    }

    /**
     *销售出库扫码
     */
    fun scan(
        barcode: String?,
        no6: String?,
        no7: String?,
        pda: String?,
        no9: String?,
        no10: String?
    ) {
        view?.showLoading()
        LogUtils.d(
            tag,
            "销售出库-开始查询扫描到的数据 barcode=$barcode,no6=$no6,no7=$no7,pad=$pda,no9=$no9,no10=$no10"
        )
        DataApi.api.maleChuKuScan(
            ServerBean.MailChuKuScanRequest(
                mode = 11,
                barcode = barcode,
                wk_id = wkId,
                wk_name = wkName,
                no6 = no6,
                no7 = no7,
                pda = pda,
                no9 = no9,
                no10 = no10
            )
        ).enqueue(object : ApiCallback<BaseEntity<ServerBean.MailScanChuKuResponse>>() {
            override fun onSuccess(response: BaseEntity<ServerBean.MailScanChuKuResponse>?) {
                LogUtils.d(tag, "销售出库扫描成功 response=${GsonUtil.toJson(response)}")
                if (response != null && response.code == ErrorCode.CODE_NOT_ALLOW_SIMULTANEOUS_RECEIPT) {
                    //不允许多家供应商同时收料
                    view?.scanFailed(response.message)
                }

                if (response != null && response.data != null) {
                    mScanResponse = response.data?.list as MutableList<ServerBean.MailChuKuResponseItem>?
                    mDataList.clear()
                    for (itemData in response.data?.list!!) {
                        mDataList.add(
                            ServerBean.MailChuKuResponseItem(
                                id = itemData.id,
                                userId = itemData.userId, prodNo = itemData.prodNo,
                                qty = itemData.qty, preQty = itemData.preQty,
                                custId = itemData.custId, custName = itemData.custName,
                                custPo = itemData.custPo, itemNo = itemData.itemNo,
                                itemDesc = itemData.itemDesc, specs = itemData.specs, stkQty = itemData.stkQty
                            )
                        )
                    }
                    view?.notifyAdapter()
                }
                view?.dismissLoading()
            }

            override fun onError(t: Throwable?, code: Int, message: String?) {
                LogUtils.d(tag, "销售出库扫描失败 t=${t?.message},code=$code,message=$message")
                view?.dismissLoading()
                view?.scanFailed(message)
            }
        })
    }

    /**
     *销售出库提交
     */
    fun commit(
        no6: String?,
        pda: String?
    ) {
        LogUtils.d(tag, "销售出库-开始提交修改点")
        view?.showLoading()
        DataApi.api.maleChuKuCommit(
            ServerBean.MailChuKuCommitRequest(
                mode = 12,
                wk_id = wkId,
                no6 = no6,
                wk_name = wkName,
                pda = pda
            )
        ).enqueue(object : ApiCallback<BaseEntity<ServerBean.MailChuKuCommit>>() {
            override fun onSuccess(response: BaseEntity<ServerBean.MailChuKuCommit>?) {
                mDataList.clear()
                view?.dismissLoading()
                view?.commitSuccess()
            }

            override fun onError(t: Throwable?, code: Int, message: String?) {
                view?.dismissLoading()
                view?.commitFailed(message)
            }

        })
    }

    /**
     *删除单挑临时表
     */
    fun deleteTempData(position:Int,id: Long) {
        LogUtils.d(tag, "删除单挑临时表 $id")
        view?.showLoading()
        DataApi.api.deleteSalePoTemp(ServerBean.PurchasePODeleteRequest(id)).enqueue(object : ApiCallback<BaseEntity<Any>>() {
            override fun onSuccess(response: BaseEntity<Any>?) {
                LogUtils.d(tag, "单条临时表删除成功 id=$id response=${GsonUtil.toJson(response)}")
                mDataList.removeAt(position)
                view?.dismissLoading()
                view?.deleteTempSuccess()
            }

            override fun onError(t: Throwable?, code: Int, message: String?) {
                LogUtils.d(
                    tag,
                    "单条临时表删除失败 id=$id,t=${t?.message},code=$code,message=$message"
                )
                view?.dismissLoading()
                view?.deleteTempFailed(message)
            }
        })
    }

    fun modifyTempData(id: Long, qty: Int, preQty: Int) {
        LogUtils.d(tag, "编辑单条临时表 id=$id,qty=$qty,preQty=$preQty")
        DataApi.api.updateSalePoTemp(
            ServerBean.UpdateSalePoTempRequest(
                id = id,
                qty = qty,
                preQty = preQty
            )
        )
            .enqueue(object : ApiCallback<BaseEntity<Any>>() {
                override fun onSuccess(response: BaseEntity<Any>?) {
                    LogUtils.d(tag, "临时表编辑成功 response=${GsonUtil.toJson(response)}")
                    view?.modifyTempSuccess()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(tag, "临时表编辑失败 t=${t?.message},code=$code,message=$message")
                    view?.modifyTempFailed(message)
                }
            })
    }
}